<template>
    <Modal v-model="visible"
           v-bind="$attrs"
           :styles="modalStyles"
           v-on="$listeners"
    >
      <Row v-if="itemType === 2">
        <Button type="primary" @click="importFile">选择文件</Button>
        <vxe-grid ref="xGrid"
                  class="mt15"
                  height="400"
                  border
                  :columns="tableColumn"
                  :data="data">
        </vxe-grid>
      </Row>
      <Row v-else>
        <Transfer
          :data="data"
          :target-keys="targets"
          :list-style="listStyle"
          filterable
          @on-change="handleChange">
        </Transfer>
      </Row>
    </Modal>
</template>

<script>
  export default {
    name: 'ModalItemList',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      itemType: {
        type: Number,
        default: 1
      },
      data: {
        type: Array
      }
    },
    data() {
      return {
        targets: [],
        listStyle: {
          width: '100%',
          height: '400px'
        },
        modalStyles: {
          zIndex: 100,
          width: '720px'
        },
        tableColumn: [
          { type: 'checkbox', width: 60 },
          { field: 'code', title: '商品编码' },
          { field: 'name', title: '商品名称' },
        ],
      }
    },
    created() {
    },
    methods: {
      importFile() {
        this.$refs.xGrid.readFile({
          types: ['xls', 'xlsx']
        }).then(params => {
          const { files } = params
          const fileReader = new FileReader()
          fileReader.onload = (ev) => {
            const data = ev.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1)
            const tableData = []
            // 解析数据
            csvData.split('\n').forEach((vRow) => {
              if (vRow) {
                const vCols = vRow.split(',')
                const item = {}
                vCols.forEach((val, cIndex) => {
                  const column = this.tableColumn[cIndex]
                  if (column.field) {
                    item[column.field] = val
                  }
                })
                tableData.push(item)
              }
            })
            this.tableData = tableData
          }
          fileReader.readAsBinaryString(files[0])
        })
      }
    },
  }
</script>

<style scoped>
  .ivu-transfer {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
</style>
